const Controller = require('../core/base_controller');

const path = require('path')
const fs = require('mz/fs');
const assert = require('assert')
const _ = require('lodash')

class AppController extends Controller {

    //钉钉登录
    async loginDD() {
        const { app, app: { dd }, ctx } = this;
        let { code } = this.param

        //
        assert(code, '未获取到授权码！')

        //通过钉钉 交换userid
        let userinfo = await dd.user.getuserinfo({ code })
        let userid = userinfo.userid
        //let userid = '0109353356999048088'

        await this.checkLogin({ userid }, '用户不存在，请通知管理员先同步此用户！')
    }

    //后台登录
    async login() {
        const { app, app: { dd }, ctx } = this;

        let { username, password } = this.param

        await this.checkLogin({ mobile: username, password: password }, '用户名或者密码错误！')
    }


    //根据userId获取用户信息
    async checkLogin(where, message) {
        const { app, ctx, service: { user } } = this
        let loginUser = await user.findOne(where)
        assert(loginUser, message)

        let sessionUser = {
            userid: loginUser.userid,
            username: loginUser.name,
            role: loginUser.role,
            department: loginUser.department,
        };

        //session.user = sessionUser

        //生成登录Token
        const token = app.jwt.sign(sessionUser, app.config.jwt.secret);
        ctx.cookies.set('Authorization', token);
        this.success(token)
    }

    //注销登录
    async logout() {
        const { ctx } = this
        ctx.cookies.set('Authorization', null);
        this.success()
    }

    //渲染home页面
    async home() {
        let { agentId, page = 'pc' } = this.param
        let config = '<script></script>'
        if (agentId) {
            //获取钉钉PC免登数据
            let ret = await this.app.dtalk.auth.getSingture(this.ctx.request.href)
            ret.agentId = agentId
            config = `<script>window.__config = ${JSON.stringify(ret)}</script>`
        }

        this.ctx.body = await this.ctx.renderString(config);
        this.ctx.body += await this.ctx.renderView(`${page}/index`);
    }

    //同步用户
    async asyncUser() {
        const { service: { dd } } = this
        let ret = await dd.getUser()

        this.success(ret);
    }

}
module.exports = AppController;
